import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_module/entities/Commodity.dart';
import 'package:flutter_module/global/colors.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_module/entities/CourseItemEn.dart';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        //appBar: AppBar(
        //  backgroundColor: Colors.black26,
        //  title: Text('container'),
        //),
        body: RecommendTab(),
      ),
    );
  }
}

class RecommendTab extends StatefulWidget {
  RecommendTab({Key key}) : super(key: key);

  @override
  _RecommendTabState createState() {
    return _RecommendTabState();
  }
}

class _RecommendTabState extends State<RecommendTab>
    with AutomaticKeepAliveClientMixin {
  CourseItemEn _courseItemEn, _courseItemEn1, _courseItemEn2, _courseItemEn3;
  List<CourseItemEn> _techniqueData = [];
  List<String> imgList = [
    'https://img1.baidu.com/it/u=162254320,141427240&fm=253&fmt=auto&app=138&f=JPEG?w=1920&h=500',
    'https://img2.baidu.com/it/u=1437427902,1754695840&fm=253&fmt=auto&app=138&f=JPEG?w=1280&h=333',
  ];

  @override
  void initState() {
    super.initState();

    _courseItemEn = new CourseItemEn(
        1,
        'http://photogz.photo.store.qq.com/psc?/V54ETsN62Rdw772wFsNq0jEkXI4LU2rF/05RlWl8gsTOH*Z17MtCBzDeGzH45MAaltFu*8GPsRbcKLgTzlOYBPzTRRs67V3i.c6p.chOGdWv5xdLen5fdXg!!/m&bo=NgJ4AjYCeAIRADc!&rf=mood_app',
        "保护",
        1,
        "103",
        "https://img0.baidu.com/it/u=178892670,2966992691&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400",
        "The Mentevice");
    _courseItemEn1 = new CourseItemEn(
        1,
        'http://photogz.photo.store.qq.com/psc?/V54ETsN62Rdw772wFsNq0jEkXI4LU2rF/05RlWl8gsTOH*Z17MtCBzAwS0MxrZm1k*1zjq0ea*xzKT8bI2OfaEDjQx7K*xuaaBcvpJIAE3XnW4QBIWwMRpQ!!/m&bo=xgLRAsYC0QIRADc!&rf=mood_app',
        "城市里的幻梦人",
        1,
        "1.2ETH",
        "https://img2.baidu.com/it/u=1652427738,3139747163&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
        "Elbeau");
    _courseItemEn2 = new CourseItemEn(
        1,
        'http://photogz.photo.store.qq.com/psc?/V54ETsN62Rdw772wFsNq0jEkXI4LU2rF/05RlWl8gsTOH*Z17MtCBzN8evfj4Q6iSd5.*oY2Bq9QKCSUjCv9wTWFmaIMElEdsXPkUjjn*89pByc*e.PMlWw!!/m&bo=TAK8AkwCvAIRADc!&rf=mood_app',
        "戴口罩的杰克",
        1,
        "2.3ETH",
        "https://img2.baidu.com/it/u=2391726625,2951775714&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500",
        "0xd1c441");
    _courseItemEn3 = new CourseItemEn(
        1,
        'http://photogz.photo.store.qq.com/psc?/V54ETsN62Rdw772wFsNq0jEkXI4LU2rF/05RlWl8gsTOH*Z17MtCBzEW1qlG0A.RqshcU7*1S*ZQxF57TOBocjRINGuM7PLiACGGSySn2gzuWI.GVig8sew!!/m&bo=fwLFAn8CxQIRADc!&rf=mood_app',
        "差点被这个世界打败",
        1,
        "3.2ETH",
        "https://img0.baidu.com/it/u=4096999652,2870060546&fm=253&fmt=auto&app=138&f=JPEG?w=517&h=500",
        "sov");
    _techniqueData.add(_courseItemEn);
    _techniqueData.add(_courseItemEn1);
    _techniqueData.add(_courseItemEn2);
    _techniqueData.add(_courseItemEn3);
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget _swiperWidget() {
    return Container(
      width: double.infinity,
      height: ScreenUtil().setHeight(362),
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(20),
          right: ScreenUtil().setHeight(20),
          top: ScreenUtil().setHeight(10)),
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.network(
              imgList[index],
              fit: BoxFit.cover,
            ),
          );
        },
        pagination: SwiperPagination(
          alignment: Alignment.bottomRight,
          builder: SwiperCustomPagination(
            builder: (BuildContext context, SwiperPluginConfig config) {
              return CustomP(config.activeIndex, imgList.length);
            },
          ),
        ),
        itemCount: imgList.length,
        autoplay: true,
        onIndexChanged: (int index) {
          // Provider.of<SetBgProvider>(context).setBgColor(index);
        },
      ),
    );
  }

  Widget _topWidget() {
    return Container(
      width: double.infinity,
      height: ScreenUtil().setHeight(230),
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(60)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(210),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/images/shangcheng.png',
                  width: ScreenUtil().setHeight(155),
                  height: ScreenUtil().setHeight(155),
                  fit: BoxFit.fitHeight,
                ),
                Text(
                  '链上商城',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.white,
                  ),
                )
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(210),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipOval(
                  child: Image.asset(
                    'assets/images/vip.png',
                    width: ScreenUtil().setHeight(155),
                    height: ScreenUtil().setHeight(155),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  '会员中心',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.white,
                  ),
                )
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(210),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipOval(
                  child: Image.asset(
                    'assets/images/rank.png',
                    width: ScreenUtil().setHeight(155),
                    height: ScreenUtil().setHeight(155),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  '销量排行榜',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.white,
                  ),
                )
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(200),
            height: ScreenUtil().setHeight(210),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                ClipOval(
                  child: Image.asset(
                    'assets/images/jiangli.png',
                    width: ScreenUtil().setHeight(155),
                    height: ScreenUtil().setHeight(155),
                    fit: BoxFit.cover,
                  ),
                ),
                Text(
                  '奖励中心',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(34),
                    color: Colors.white,
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _titleWidget(value, num) {
    return Container(
      margin: EdgeInsets.fromLTRB(
        ScreenUtil().setWidth(46),
        ScreenUtil().setHeight(50),
        ScreenUtil().setWidth(0),
        ScreenUtil().setHeight(0),
      ),
      height: ScreenUtil().setHeight(74),
      child: Stack(
        children: [
          Positioned(
            bottom: 0,
            left: 0,
            child: Container(
              height: ScreenUtil().setHeight(14),
              width: ScreenUtil().setWidth(47) * num,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                    Radius.circular(ScreenUtil().setHeight(7))),
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.center,
                  stops: [0.0, 1.0],
                  colors: [AppColors.primary, Color(0x542DCA97)],
                ),
              ),
            ),
          ),
          Positioned(
            left: 0,
            top: 0,
            child: Text(
              value,
              style: TextStyle(
                fontSize: ScreenUtil().setSp(52),
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Positioned(
              bottom: 0,
              right: 0,
              child: Padding(
                padding: EdgeInsets.only(right: ScreenUtil().setWidth(35)),
                child: Text(
                  '查看全部>',
                  style: TextStyle(
                    fontSize: ScreenUtil().setSp(45),
                    color: AppColors.subtext,
                  ),
                ),
              ))
        ],
      ),
    );
  }

  Widget _courseItemWidget(CourseItemEn courseItemEn) {
    var itemWidth = (ScreenUtil().screenWidth - 30) / 2;

    return InkWell(
      onTap: () {
        Navigator.pushNamed(context, 'productDetail');
      },
      child: Container(
        width: itemWidth, //实现在wrap中平铺,高度自适应
        decoration: BoxDecoration(
          color: Color(0xff182643),
          boxShadow: [
            BoxShadow(
              color: Colors.black26,
              offset: Offset(-1, 1.0),
              blurRadius: 1.0,
              spreadRadius: 0.6,
            ),
          ],
          borderRadius: BorderRadius.all(Radius.circular(8)),
        ),
        child: Column(
          children: <Widget>[
            Container(
              width: double.infinity,
              child: AspectRatio(
                aspectRatio: 1 / 1, //防止服务器返回的图片高度不一致
                child: ClipRRect(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(8),
                    topRight: Radius.circular(8),
                  ),
                  child: Image.network(
                    courseItemEn.cover,
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            Align(
              alignment: Alignment.bottomLeft,
              child: Container(
                margin: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(20),
                  ScreenUtil().setHeight(0),
                  ScreenUtil().setWidth(0),
                  ScreenUtil().setHeight(0),
                ),
                child: Text(
                  courseItemEn.name,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            Align(
              alignment: Alignment.bottomLeft,
              child: Container(
                margin: EdgeInsets.fromLTRB(
                  ScreenUtil().setWidth(20),
                  ScreenUtil().setHeight(0),
                  ScreenUtil().setWidth(0),
                  ScreenUtil().setHeight(0),
                ),
                child: Text(
                  '${courseItemEn.price}',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(
                  top: ScreenUtil().setHeight(20),
                  bottom: ScreenUtil().setHeight(20)),
              child: Row(
                children: <Widget>[
                  Align(
                      alignment: Alignment.centerLeft,
                      child: Row(
                        children: [
                          SizedBox(
                            width: ScreenUtil().setWidth(20),
                          ),
                          ClipOval(
                            child: Image.network(courseItemEn.headImg,
                                width: ScreenUtil().setWidth(60),
                                height: ScreenUtil().setWidth(60),
                                fit: BoxFit.cover),
                          ),
                          Text(
                            courseItemEn.nickName,
                            style: TextStyle(
                              fontSize: 13,
                              color: Colors.white,
                            ),
                          )
                        ],
                      )),
                  Expanded(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Image.asset(
                          'assets/images/png.png',
                          width: ScreenUtil().setHeight(70),
                          height: ScreenUtil().setHeight(50),
                          fit: BoxFit.fitHeight,
                        ),
                        SizedBox(
                          width: ScreenUtil().setWidth(30),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );

    return ListView(
      children: AnimationConfiguration.toStaggeredList(
        duration: const Duration(milliseconds: 575),
        childAnimationBuilder: (widget) => SlideAnimation(
          horizontalOffset: MediaQuery.of(context).size.width / 2,
          child: FadeInAnimation(child: widget),
        ),
        children: [
          _swiperWidget(),
          _topWidget(),
          Container(
            padding: EdgeInsets.all(10),
            child: Wrap(
              runSpacing: 10,
              spacing: 10,
              children: _techniqueData
                  .asMap()
                  .keys
                  .map((index) => _courseItemWidget(_techniqueData[index]))
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class CustomP extends StatelessWidget {
  var _currentIndex;
  int maxnum;

  CustomP(this._currentIndex, this.maxnum);

  @override
  Widget build(BuildContext context) {
    //debugPaintSizeEnabled=true;
    return Container(
      width: 0.05 * ScreenUtil().screenWidth * maxnum,
      height: ScreenUtil().setHeight(3),
      child: GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: this.maxnum,
            childAspectRatio: 2 / 1,
            crossAxisSpacing: ScreenUtil().setWidth(4)),
        itemBuilder: (BuildContext context, int index) {
          return Container(
            decoration: BoxDecoration(
                color:
                    _currentIndex == index ? Color(0xffF2453E) : Colors.white,
                borderRadius: BorderRadius.circular(1)),
          );
        },
        itemCount: this.maxnum,
      ),
    );
  }
}
